#include "udp_client.hpp"

void usage(std::string proc)
{
    std::cout << "Usage:\n\t" << proc << " serverip" << " serverport\n" << std::endl;
}

void* recver(void* args)
{
    int sock = *(static_cast<int*>(args));
    while(true)
    {
        //4.从服务器接收数据
        char buffer[2048];
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        int n = recvfrom(sock, buffer, sizeof(buffer)-1, 0, (struct sockaddr*)&temp, &len);
        if(n > 0)
        {
            buffer[n] = 0;
            std::cout << buffer << std::endl;
        }
    }
}

// ./udp_server 0.0.0.0 8080
int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        usage(argv[0]);
        exit(USAGE_ERR);
    }
    std::string serverip = argv[1];
    uint16_t serverport = atoi(argv[2]);

    //1.创建套接字接口，打开网络文件
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if(sock < 0)
    {
        std::cerr << "create socket error" << std::endl;
        exit(USAGE_ERR);
    }
    //2.绑定ip和端口号，OS自动绑定，不用手动bind

    //3.向服务器发送数据
        //3.1明确服务器是谁
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    // 创建线程负责从服务器接收数据，主线程负责发送数据
    pthread_t tid;
    pthread_create(&tid, nullptr, recver, &sock);

    while(true)
    {
        //3.2用户输入数据后发送
        std::string message;
        std::cerr << "[Please Enter Your Massage]# ";
        //std::cin >> message;
        std::getline(std::cin, message);
        sendto(sock, message.c_str(), message.size(), 0, (struct sockaddr*)&server, sizeof(server));

        // 接收数据功能移动到新建线程部分
        // //4.从服务器接收数据
        // char buffer[2048];
        // struct sockaddr_in temp;
        // socklen_t len = sizeof(temp);
        // int n = recvfrom(sock, buffer, sizeof(buffer)-1, 0, (struct sockaddr*)&temp, &len);
        // if(n > 0)
        // {
        //     buffer[n] = '\0';
        //     std::cout << "server echo# " << buffer << std::endl;
        // }
    }

    close(sock);

    return 0;
}